package com.yupi.yuoj.judge.codesandbox.strategy;

import cn.hutool.json.JSONUtil;
import com.yupi.yuoj.model.dto.question.JudgeCase;
import com.yupi.yuoj.model.dto.question.JudgeConfig;
import com.yupi.yuoj.judge.codesandbox.model.JudgeInfo;
import com.yupi.yuoj.model.entity.Question;
import com.yupi.yuoj.model.enums.JudgeInfoMessageENUM;

import java.util.List;
import java.util.Optional;

/**
 * @author hch
 * @version 1.0
 * @description 默认策略模式
 * @date 2024/6/25 17:44
 */

public class JavaJudgeStrategy implements JudgeStrategy {


    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {
        List<String> outputList = judgeContext.getOutputList();
        List<String> inputList = judgeContext.getInputList();
        Question question = judgeContext.getQuestion();
        String judgeConfig = question.getJudgeConfig();
        JudgeConfig config = JSONUtil.toBean(judgeConfig, JudgeConfig.class);
        String judgeCase = question.getJudgeCase();
        List<JudgeCase> judgeCases = JSONUtil.toList(judgeCase, JudgeCase.class);

        JudgeInfo judgeInfo = judgeContext.getJudgeInfo();
        String message = judgeInfo.getMessage();

        Long time = Optional.ofNullable(judgeInfo.getTime()).orElse(0L);
        Long memory = Optional.ofNullable(judgeInfo.getMemory()).orElse(0L);

        JudgeInfo info = new JudgeInfo();
//        info.setMessage(JudgeInfoMessageENUM.Accepted.getValue());
        info.setMessage(JudgeInfoMessageENUM.Accepted.getValue());
        info.setMemory(memory);
        info.setTime(time);

        JudgeInfoMessageENUM judgeInfoMessageENUM = null;
        if (outputList.size() != inputList.size()) {
            judgeInfoMessageENUM = JudgeInfoMessageENUM.WRONG_ANSWER;
            info.setMessage(judgeInfoMessageENUM.getValue());
            return info;
        }

        //判断结果是否正确
        for (int i = 0; i < outputList.size(); i++) {
            if (!outputList.get(i).equals(judgeCases.get(i).getOutput())) {
                judgeInfoMessageENUM = JudgeInfoMessageENUM.WRONG_ANSWER;
                info.setMessage(judgeInfoMessageENUM.getValue());
                return info;
            }
        }

        //判断是否有超过限制
        Long JAVA_TIME = 100L;
        if (config.getMemoryLimit() + JAVA_TIME < memory) {
            judgeInfoMessageENUM = JudgeInfoMessageENUM.MEMORY_LIMIT_EXCEEDED;
            info.setMessage(judgeInfoMessageENUM.getValue());
            return info;
        }
        if (config.getTimeLimit() < time) {
            judgeInfoMessageENUM = JudgeInfoMessageENUM.TIME_LIMIT_EXCEEDED;
            info.setMessage(judgeInfoMessageENUM.getValue());
            return info;
        }
        return info;
    }
}